<?php

namespace app\weixin\controller;

use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Text;
use think\Config;
use think\Controller;
use app\common\model\miniapp\Payorder;

class Payment extends Controller
{

    private $payment;
    public function __construct()
    {
        
        $payment_config=[
            'app_id'=Config::get('wxpay.appid'),
            'mch_id'=>Config::get('wxpay.mchid'),
            'key'=>Config::get('wxpay.key'),
            'notify_url'=>'/weixin/payment/notify'

        ];
        $this->payment=Factory::payment($payment_config);

    }
    
    /**
     * 微信支付统一下单
     *
     * @return void
     * @author 
     **/
    public function unify($member_id,$total_fee,$out_trade_no,$trade_type='NATIVE',$body='充值',$product_id=1)
    {
        $result=$this->payment->order->unify([
            'totale_fee'=>$total_fee*100,
            'trade_type'=>$trade_type,
            'product_id'=>$product_id,
            'body'=>$body,
            'out_trade_no'=>$out_trade_no

        ]);
        Payorder::create([
            'total_fee'=>$total_fee,
            'out_trade_no'=>$out_trade_no,
            'member_id'=>$member_id

        ]);
        return $result;
    }
    /**
     * 微信支付回调
     *
     * @return void
     * @author 
     **/
    public function notify()
    {
        $response=$this->payment->handlePaidNotify(function($message,$fail){
            $order=Payorder::get(['out_trade_no'=>$message['out_trade_no']]);
            if(!$order||$order->state==1){
                return true;
            }
            if($message['return_code']==='SUCCESS'$$message['resulst_code']==='SUCCESS'){
                
                $order->update_time=time();
                $order->state=1;
            }else{
                return $fail('通信失败')；
            }
            $order->save();
            return true; 

        });
        $response->send();


    }

}
